<template>
  <el-dialog
    title="消息转发"
    v-model="dialogVisible"
    width="520px"
    :append-to-body="true"
    :close-on-click-modal="false"
    center
  >
    <div class="temp-forward-content">
      <p>您将转发以下消息：</p>
      <div class="message-preview">
        <div v-if="message && message.type === 0" class="text-message">
          {{ message.content }}
        </div>
        <div v-else-if="message && message.type === 1" class="image-message">
          [图片消息]
        </div>
        <div v-else-if="message && message.type === 2" class="file-message">
          [文件消息] 
        </div>
        <div v-else class="unknown-message">
          [未知类型消息]
        </div>
      </div>
      
      <el-divider></el-divider>
      
      <p>请选择转发对象：</p>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="最近会话" name="recents">
          <el-input
            placeholder="搜索最近会话"
            v-model="searchQuery"
            prefix-icon="Search"
            clearable
            class="search-input"
          ></el-input>
          
          <div class="contact-list">
            <div v-for="chat in filteredChats" :key="chat.id" class="contact-item">
              <el-checkbox v-model="chat.selected" class="contact-checkbox">
                <div class="contact-info">
                  <head-image :url="chat.headImage" :name="chat.showName" :size="40"></head-image>
                  <div class="contact-details">
                    <div class="name">{{ chat.showName }}</div>
                    <div class="chat-type" v-if="chat.type">{{ chat.type === 'GROUP' ? '群聊' : '私聊' }}</div>
                  </div>
                </div>
              </el-checkbox>
            </div>
            <div v-if="filteredChats.length === 0" class="empty-list">
              无最近会话
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="好友" name="friends">
          <el-input
            placeholder="搜索好友"
            v-model="searchQuery"
            prefix-icon="Search"
            clearable
            class="search-input"
          ></el-input>
          
          <div class="contact-list">
            <div v-for="friend in filteredFriends" :key="friend.id" class="contact-item">
              <el-checkbox v-model="friend.selected" class="contact-checkbox">
                <div class="contact-info">
                  <head-image :url="friend.headImage" :name="friend.nickName" :size="40"></head-image>
                  <div class="contact-details">
                    <div class="name">{{ friend.nickName }}</div>
                  </div>
                </div>
              </el-checkbox>
            </div>
            <div v-if="filteredFriends.length === 0" class="empty-list">
              无好友数据
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="群聊" name="groups">
          <el-input
            placeholder="搜索群聊"
            v-model="searchQuery"
            prefix-icon="Search"
            clearable
            class="search-input"
          ></el-input>
          
          <div class="contact-list">
            <div v-for="group in filteredGroups" :key="group.id" class="contact-item">
              <el-checkbox v-model="group.selected" class="contact-checkbox">
                <div class="contact-info">
                  <head-image :url="group.headImage" :name="group.name" :size="40"></head-image>
                  <div class="contact-details">
                    <div class="name">{{ group.name }}</div>
                  </div>
                </div>
              </el-checkbox>
            </div>
            <div v-if="filteredGroups.length === 0" class="empty-list">
              无群聊数据
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="!hasSelection">
          转发 ({{selectedCount}})
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import HeadImage from '../common/HeadImage.vue';

export default {
  name: 'TempForwardDialog',
  components: {
    HeadImage
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    message: {
      type: Object,
      required: true
    }
  },
  emits: ['update:modelValue', 'forward-complete'],
  data() {
    return {
      activeTab: 'recents',
      searchQuery: '',
      friends: [],
      groups: [],
      chats: []
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit('update:modelValue', val);
      }
    },
    selectedCount() {
      return this.selectedFriends.length + this.selectedGroups.length + this.selectedChats.length;
    },
    hasSelection() {
      return this.selectedCount > 0;
    },
    filteredFriends() {
      if (!this.searchQuery) return this.friends;
      
      return this.friends.filter(friend => 
        friend.nickName && friend.nickName.toLowerCase().includes(this.searchQuery.toLowerCase())
      );
    },
    filteredGroups() {
      if (!this.searchQuery) return this.groups;
      
      return this.groups.filter(group => 
        group.name && group.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      );
    },
    filteredChats() {
      if (!this.searchQuery) return this.chats;
      
      return this.chats.filter(chat => 
        chat.showName && chat.showName.toLowerCase().includes(this.searchQuery.toLowerCase())
      );
    },
    selectedFriends() {
      return this.friends.filter(friend => friend.selected);
    },
    selectedGroups() {
      return this.groups.filter(group => group.selected);
    },
    selectedChats() {
      return this.chats.filter(chat => chat.selected);
    }
  },
  watch: {
    modelValue(val) {
      if (val) {
        this.loadData();
      }
    },
    activeTab() {
      this.searchQuery = '';
    }
  },
  methods: {
    loadData() {
      this.chats = this.$store.state.chatStore.chats.map(chat => ({
        ...chat,
        selected: false,
        id: chat.targetId,
        headImage: chat.headImage || '',
        showName: chat.showName || (chat.type === 'GROUP' ? '群聊' : '好友')
      }));
      
      this.friends = this.$store.state.friendStore.friends.map(friend => ({
        ...friend,
        selected: false,
        headImage: friend.headImage || ''
      }));
      
      this.groups = this.$store.state.groupStore.groups.map(group => ({
        ...group,
        selected: false,
        headImage: group.headImage || ''
      }));
      
      this.searchQuery = '';
      this.activeTab = 'recents';
    },
    handleConfirm() {
      if (this.selectedCount === 0) {
        this.$message.warning('请选择至少一个转发对象');
        return;
      }
      
      const targets = [
        ...this.selectedChats.map(chat => ({
          targetId: chat.targetId,
          showName: chat.showName,
          type: chat.type,
          headImage: chat.headImage
        })),
        ...this.selectedFriends.map(friend => ({
          targetId: friend.id,
          showName: friend.nickName,
          type: 'PRIVATE',
          headImage: friend.headImage
        })),
        ...this.selectedGroups.map(group => ({
          targetId: group.id,
          showName: group.name,
          type: 'GROUP',
          headImage: group.headImage
        }))
      ];
      
      const uniqueTargets = this.removeDuplicateTargets(targets);
      
      this.$emit('forward-complete', uniqueTargets);
      
      this.$message.success(`已将消息转发给${uniqueTargets.length}个联系人`);
      
      this.dialogVisible = false;
    },
    
    removeDuplicateTargets(targets) {
      const uniqueMap = new Map();
      
      targets.forEach(target => {
        const key = `${target.type}-${target.targetId}`;
        uniqueMap.set(key, target);
      });
      
      return Array.from(uniqueMap.values());
    }
  }
}
</script>

<style scoped>
.temp-forward-content {
  width: 100%;
}

.message-preview {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 12px;
  margin-top: 8px;
  margin-bottom: 8px;
  max-height: 80px;
  overflow-y: auto;
}

.search-input {
  margin-bottom: 16px;
}

.contact-list {
  height: 300px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.contact-item {
  padding: 10px 16px;
  border-bottom: 1px solid #e4e7ed;
}

.contact-item:last-child {
  border-bottom: none;
}

.contact-checkbox {
  width: 100%;
}

.contact-info {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.contact-details {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
}

.name {
  font-size: 14px;
  font-weight: 500;
}

.chat-type {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.empty-list {
  padding: 20px;
  text-align: center;
  color: #909399;
}
</style> 